import { SERVICE_API } from "@/components/CommonConstants"
import useRpcApi from "@/hooks/useRpcApiHook"
import { PlusOutlined } from "@ant-design/icons"
import { ActionType, FormInstance, ProColumns, ProTable } from "@ant-design/pro-components"
import { Button, Popconfirm, message } from "antd"
import { useRef, useState } from "react"
import { UserFormModal } from "./UserFormModal"
import RoleBindModal from "./RoleBoundModal"
import RoleBoundModal from "./RoleBoundModal"


interface UserModel {
    id: number
    userid: string
    username: string
    display_name: string
    mobile: string
    create_time: string
    update_time: string
    status: string
    status_label: string
}


type PageItem = UserModel;

function UserSettings() {
    const actionRef = useRef<ActionType>()
    const formRef = useRef<FormInstance>()
    const { pageQuery, apiRpc } = useRpcApi()


    const [formData, setFormData] = useState<PageItem>({
        id: 0,
        userid: "",
        username: "",
        display_name: "",
        mobile: "",
        create_time: "",
        update_time: "",
        status: "",
        status_label: "",
    })
    const [openAddUserModal, setOpenAddUserModal] = useState(false)
    const [openRoleBoundModal, setOpenRoleBoundModal] = useState(false)


    const queryTableData = (params: any): Promise<any> => {
        const { current, pageSize } = params
        const _params = { ...params }
        delete _params.current
        delete _params.pageSize
        return pageQuery(SERVICE_API.USER_QUERY_PAGE, current, pageSize, _params)
    }

    // 定义表格列
    const columns: ProColumns<PageItem>[] = [
        {
            title: "用户名",
            dataIndex: "username",
            key: "username",
            width: "200px",
            ellipsis: true,
            editable: false, // 是否可编辑
        },
        {
            title: "姓名",
            dataIndex: "display_name",
            key: "display_name",
            width: "200px",
            ellipsis: true,
        },
        {
            title: "手机号",
            dataIndex: "mobile",
            key: "mobile",
            width: "150px",
            ellipsis: true,
            search: false,
        },
        {
            title: "状态",
            dataIndex: "status",
            key: "status",
            width: "100px",
            ellipsis: true,
            editable: false,
            valueEnum: {
                Active: {
                    text: "激活",
                    status: "Active",
                },
                Inactive: {
                    text: "未激活",
                    status: "Inactive",
                },
                Disabled: {
                    text: "禁用",
                    status: "Disabled",
                },
            },
        },
        {
            title: "创建时间",
            dataIndex: "create_time",
            key: "create_time",
            width: "180px",
            ellipsis: true,
            search: false,
            editable: false,
        },
        {
            title: "更新时间",
            dataIndex: "update_time",
            key: "update_time",
            width: "180px",
            ellipsis: true,
            search: false,
            editable: false,
        },
        {
            title: "操作",
            valueType: "option",
            key: "option",
            render: (text, record, _, action) => [
                <a
                    onClick={() => {
                        action?.startEditable?.(record.id)
                    }}
                >
                    编辑
                </a>,
                <a
                    onClick={() => {
                        setFormData(record)
                        setOpenRoleBoundModal(true)
                    }}
                >
                    角色
                </a>,
                <Popconfirm
                    title=""
                    description="删除此项?"
                    onConfirm={() => {
                        deleteRow(undefined, record)
                    }}
                    onCancel={() => {
                        console.log(record, "   act  ", action)
                    }}
                    cancelText="取消"
                    okText="确定"
                >
                    <a>删除</a>
                </Popconfirm>,
                <Popconfirm
                    title=""
                    description={() => {
                        return record.status !== "Disabled" ? "确认禁用该账号?" : "确认启用该账号?"
                    }}
                    onConfirm={() => {
                        toggleStatus(undefined, {
                            userid: record.userid,
                            action: record.status === "Disabled" ? "enable" : "disable",
                        })
                    }}
                    onCancel={() => {
                        console.log(record, "   act  ", action)
                    }}
                    cancelText="取消"
                    okText="确定"
                >
                    {record.status !== "Disabled" ? <a>禁用</a> : <a>启用</a>}
                </Popconfirm>,
            ],
        },
    ]



    function updateRow(rowKey: any, row: PageItem) {
        apiRpc(SERVICE_API.USER_UPDATE, row)
            .then(
                () =>
                    // 刷新
                    actionRef?.current?.reload(),
            )
            .catch(err => {
                message.error(`${err.message}`)
                // 保持编辑状态
                actionRef?.current?.startEditable(rowKey)
            })
    }

    /**
     * 删除操作
     * @param key
     * @param row
     */
    function deleteRow(key: any | undefined, row: any) {
        // 删除的回调函数
        apiRpc(SERVICE_API.USER_DELETE, row).catch(err => {
            message.error(`${err.message}`)
        })
        actionRef?.current?.reload()
    }

    /**
     * 切换状态
     *
     * @param key
     * @param params
     */
    function toggleStatus(key: any | undefined, params: any) {
        // 删除的回调函数
        apiRpc(SERVICE_API.USER_STATUS_TOGGLE, params).catch(err => {
            message.error(`${err.message}`)
        })
        actionRef?.current?.reload()
    }

    return (
        <div>
            <UserFormModal
                open={openAddUserModal}
                formData={formData}
                handleCancel={() => setOpenAddUserModal(false)}
                handleOk={() => {
                    setOpenAddUserModal(false)
                    actionRef?.current?.reload()
                }}
            />
            <RoleBoundModal open={openRoleBoundModal}
                user={formData}
                handleCancel={() => setOpenRoleBoundModal(false)}
                handleOk={() => setOpenRoleBoundModal(false)}
            />
            <ProTable<PageItem>
                actionRef={actionRef}
                cardBordered
                formRef={formRef}
                rowKey={"id"}
                scroll={{
                    x: "max-content",
                    y: "calc(100vh - 400px)",
                }}
                bordered
                form={{}}
                columns={columns}
                size={"small"}
                request={params => queryTableData(params)}
                toolBarRender={() => [
                    <Button key="primary" type="primary" onClick={() => setOpenAddUserModal(true)}>
                        <PlusOutlined />
                        新建
                    </Button>,
                ]}
                // 添加 editable 配置来支持行内编辑
                editable={{
                    type: "multiple",
                    deleteText: "",
                    onSave: async (key, row) => {
                        // 保存编辑内容的回调函数
                        console.log("保存", row)
                        updateRow(key, row)
                    },
                    onCancel: async (key, row) => {
                        // 取消编辑的回调函数
                        actionRef?.current?.reload()
                    },
                    onDelete: async (key, row) => {
                        deleteRow(key, row)
                    },
                }}
            ></ProTable>
        </div>
    )
}

export default UserSettings;
export type { PageItem, UserModel }